package com.example.pre.business.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.pre.business.DepartmentBusiness;
import com.example.pre.exception.ServiceException;
import com.example.pre.model.Department;
import com.example.pre.model.User;
import com.example.pre.model.vo.DepartmentVO;
import com.example.pre.service.DepartmentService;
import com.example.pre.service.UserService;

/**
 * 部门业务层实现类
 * 
 * @author Administrator
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DepartmentBusinessImpl implements DepartmentBusiness {

	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private UserService userService;

	@Override
	public Department createDepartment(String name, String description) throws Exception {
		Map<String, Object> selectMap = new HashMap<>();
		selectMap.put("name", name);
		int count = departmentService.countByCondition(selectMap);
		if (count > 0) {
			throw new ServiceException("该部门已经存在;name=" + name, "部门已存在", -401);
		}
		Department department = new Department();
		department.setName(name);
		department.setDescription(description);
		departmentService.create(department);
		return department;
	}

	@Override
	public DepartmentVO getDepartmentUsers(int departmentId) throws Exception {
		Map<String, Object> selectMap = new HashMap<>();
		Department department = departmentService.get(departmentId);
		if (department == null) {
			throw new ServiceException("该部门不存在", "部门不存在", -404);
		}
		selectMap.put("departmentId", department.getId());
		Collection<User> users = userService.listByCondition(selectMap);
		DepartmentVO departmentVO = new DepartmentVO(department, users);
		return departmentVO;
	}

	@Override
	public List<Department> getDepartments() throws Exception {
		return (List<Department>) departmentService.getAll();
	}

}
